package com.iss.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class IOHelper {
	public static boolean createFile(String path,String fileName, boolean isReplace,String content){
		boolean isSuccess = false;
		FileWriter out = null;
		File fold = new File(path);
		File file = new File(path,fileName);
		if (file.exists()&&!isReplace){
			return false;
		}
		if (file.exists()){
			file.delete();
		}
		if (!fold.exists()){
			fold.mkdirs();
		}
		try{
			out = new FileWriter(file,false);
			out.write(content);
			isSuccess = true;
		}catch(Exception e){
			isSuccess = false;
		}finally{
			try{
				if (out!=null) out.close();
			}catch(Exception e){}
		}
		return isSuccess;
	}
	
	
	public static String getURLContent(String url,String charsetDcoding) throws IOException{
		URL u_url = new URL(url);
		InputStream is = u_url.openStream();
		return Stream2String(is,charsetDcoding);
	}
	public static String getURLContent(String url) throws IOException{
		return getURLContent(url,null);
	}
	
	
	public static String Stream2String(InputStream is,String charsetDcoding)throws IOException{
		BufferedReader bis = null;
		StringBuffer result = new StringBuffer();
		try{
			if(charsetDcoding!=null){
				bis = new BufferedReader(new InputStreamReader(is,charsetDcoding));
			}else{
				bis = new BufferedReader(new InputStreamReader(is));
			}

			char[]  b  =  new  char[4096];
		    for  (int  n;  (n  =  bis.read(b))  !=  -1;)  {  
		    	result.append(new  String(b,  0,  n));  
		    }
		    
		}finally{
			try{
				if(bis!=null)bis.close();
			}catch(Exception e){}
		}
		return result.toString();
	}
	
	public static String Stream2String(InputStream is)throws IOException{
		return Stream2String(is,null);
	}
}
